<!-- 项目订单 -->
<template>
  <el-card shadow="never">
    <el-form :model="searchForm" label-width="auto" :inline="true">
      <el-row>
        <!-- <el-col :span="6">
          <el-form-item label="材料编码" style="width: 85%">
            <el-input
              v-model="searchForm.materialCode"
              placeholder="请输入 材料编码"
              size="small"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="订单编号" style="width: 85%">
            <el-input
              v-model="searchForm.orderSn"
              placeholder="请输入 订单编号"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" style="width: 85%">
            <el-select
              v-model="searchForm.projectName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 项目名称"
              :remote-method="getProjectNameList"
              size="small"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商名称" style="width: 85%">
            <el-input
              v-model="searchForm.supplierName"
              placeholder="请输入 供应商名称"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对帐状态" style="width: 85%">
            <el-select
              v-model="searchForm.projectReconciliationStatus"
              placeholder="请选择 对帐状态"
              clearable
              size="small"
            >
              <el-option
                v-for="item in OptionsDZZT"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="结算状态" style="width: 85%">
            <el-select
              v-model="searchForm.settlementStatus"
              placeholder="请选择 结算状态"
              clearable
              size="small"
            >
              <el-option
                v-for="item in OptionsJSZT"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开票状态" style="width: 85%">
            <el-select
              v-model="searchForm.projectInvoiceStatus"
              placeholder="请选择 开票状态"
              clearable
              size="small"
            >
              <el-option
                v-for="item in OptionsKPZT"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同编号" style="width: 85%">
            <el-input
              v-model="searchForm.contractNo"
              placeholder="请输入 合同编号"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" style="width: 85%">
            <el-select
              v-model="searchForm.auditStatus"
              placeholder="请选择 状态"
              clearable
              size="small"
            >
              <el-option
                v-for="item in OptionsDDZT"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="下单日期" style="width: 85%">
            <el-date-picker
              v-model="searchForm.date"
              type="daterange"
              range-separator="-"
              start-placeholder="开始"
              end-placeholder="结束"
              size="small"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button
            color="#1E3485"
            size="small"
            icon="Download"
            @click="getlist('', true)"
          >导出</el-button
          >
          <el-button
            color="#1E3485"
            :icon="Edit"
            size="small"
            @click="
              toDetail(
                { title: '新建电梯订单', action: 'add' },
                'addElevatorOrder'
              )
            "
            >新建</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getlist('1');
            "
            >搜索</el-button
          >
          <el-button
            type="default"
            size="small"
            :icon="Delete"
            @click="clearAllFields"
            >清空</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <el-form style="margin-top: 20px">
      <vxe-table
        border
        min-height="300"
        header-align="center"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true }"
        :data="ProjectOrderTableData"
        size="mini"
      >
        <vxe-column
          type="seq"
          title="序号"
          width="50"
          align="center"
          fixed="left"
        />
        <!-- <vxe-column
          field="materialCode"
          title="材料编码"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        /> -->
        <vxe-column
          field="orderSn"
          title="订单编号"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="orderName"
          title="订单名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="contractName"
          title="合同名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="projectName"
          title="项目名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="priceType"
          title="价格类型"
          width="120"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="supplierName"
          title="供应商名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="projectReconciliationStatus"
          title="对账状态"
          width="120"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="settlementStatus"
          title="结算状态"
          width="120"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="projectInvoiceStatus"
          title="开票状态"
          width="120"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="taxTotalPrice"
          title="含税总价（元）"
          width="120"
          align="right"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="receivingTime"
          title="计划收货时间"
          width="150"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="flowSubmitDate"
          title="订单下单时间"
          width="150"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="supplyConfirmDate"
          title="订单确认时间"
          width="150"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="orderStatus"
          title="状态"
          width="120"
          align="center"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column title="操作" fixed="right" width="200" align="center">
          <!-- 操作列按钮 -->
          <template #default="{ row }">
            <vxe-button
              v-if="
                row.orderStatus == '待提交' ||
                row.orderStatus == '审批驳回' ||
                row.orderStatus == '撤回' ||
                row.orderStatus == '待供应商确认驳回'
              "
              mode="text"
              @click="Submit(row)"
              >提交审批</vxe-button
            >
            <!-- <vxe-button
              v-if="row.orderStatus == '待提交' || row.orderStatus == '待提交'"
              mode="text"
              @click="dialogVisible = true"
              >回款时间</vxe-button
            > -->
            <vxe-button
              mode="text"
              @click="
                toDetail(
                  {
                    id: row.id,
                    title: row.orderName,
                    action: 'view'
                  },
                  'viewElevatorOrder'
                )
              "
              >查看</vxe-button
            >
            <vxe-button
              v-if="
                row.orderStatus == '供货中' || row.orderStatus == '供货延迟'
              "
              mode="text"
              @click="getOrderType(row)"
              >供货完成</vxe-button
            >
            <vxe-button
              v-if="
                row.orderStatus == '供货延迟' ||
                row.orderStatus == '供货完成' ||
                row.orderStatus == '供货中'
              "
              mode="text"
              @click="
                toDetail(
                  {
                    id: row.id,
                    title: row.orderName,
                    action: 'goYSQD'
                  },
                  'goYSQD'
                )
              "
              >验收清单</vxe-button
            >
            <vxe-button
              v-if="
                row.orderStatus == '待提交' ||
                row.orderStatus == '审批驳回' ||
                row.orderStatus == '撤回' ||
                row.orderStatus == '待供应商确认驳回'
              "
              mode="text"
              @click="
                toDetail(
                  {
                    id: row.id,
                    title: row.orderName,
                    action: 'edit'
                  },
                  'editElevatorOrder'
                )
              "
              >编辑</vxe-button
            >
            <vxe-button
              v-if="
                row.orderStatus == '待提交' ||
                row.orderStatus == '审批驳回' ||
                row.orderStatus == '撤回' ||
                row.orderStatus == '待供应商确认驳回'
              "
              mode="text"
              @click="del(row)"
              >删除</vxe-button
            >
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        v-model:current-page="tablePage.currentPage"
        v-model:page-size="tablePage.pageSize"
        :layouts="[
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ]"
        :total="tablePage.total"
        size="small"
        @page-change="handlePageChange"
      />
    </el-form>
    <Paymentcollectiontime :visible="dialogVisible" @close="closeSales" />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Delete, Search, Edit, View } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import { useRouter } from "vue-router";
import { getDict } from "@/api/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getprojectOrderlist,
  deleteprojectOrder,
  postsupplyFinished,
  postsubmitapproval,
  getSupplyTypeCheck
} from "@/api/ERP_OrderManage";
import { getProjectList } from "@/api/ERP_public";

import Paymentcollectiontime from "./components/dialog/Paymentcollectiontime.vue";

import { useDetail } from "./components/utils/hooks";
import {http} from "@/utils/http";
import {baseUrlApi} from "@/store/utils";
// 路由跳转
//const router = useRouter();
const { toDetail, router } = useDetail();

// 表单字段
const searchForm = reactive({
  pageIndex: 1,
  pageSize: 10,
  materialCode: "",
  orderSn: "",
  projectName: "",
  supplierName: "",
  projectReconciliationStatus: "",
  settlementStatus: "",
  projectInvoiceStatus: "",
  contractNo: "",
  auditStatus: "",
  date: []
});
onMounted(async () => {
  getDZZT();
  getDDZT();
  getKPZT();
  getJSZT();
  getlist();
});

//字典
const OptionsDZZT = reactive([]);
const OptionsDDZT = reactive([]);
const OptionsKPZT = reactive([]);
const OptionsJSZT = reactive([]);

// 对账状态
const getDZZT = (query?: string) => {
  getDict({
    key: "reconciliationStatus"
  }).then((response: any) => {
    for (const key in response.data) {
      OptionsDZZT.push({
        label: response.data[key],
        value: key
      });
    }
  });
  if (query) {
    setTimeout(() => {
      getDict;
    }, 1500);
  }
};
// 订单状态
const getDDZT = (query?: string) => {
  getDict({
    key: "orderStatus"
  }).then((response: any) => {
    for (const key in response.data) {
      OptionsDDZT.push({
        label: response.data[key],
        value: key
      });
    }
  });
  if (query) {
    setTimeout(() => {
      getDict;
    }, 1500);
  }
};
// 开票状态
const getKPZT = (query?: string) => {
  getDict({
    key: "invoiceStatusStatus"
  }).then((response: any) => {
    for (const key in response.data) {
      OptionsKPZT.push({
        label: response.data[key],
        value: key
      });
    }
  });
  if (query) {
    setTimeout(() => {
      getDict;
    }, 1500);
  }
};
// 结算状态
const getJSZT = (query?: string) => {
  getDict({
    key: "SettlementStatus"
  }).then((response: any) => {
    for (const key in response.data) {
      OptionsJSZT.push({
        label: response.data[key],
        value: key
      });
    }
  });
  if (query) {
    setTimeout(() => {
      getDict;
    }, 1500);
  }
};

// 获取项目订单列表
const getlist = async(query?: string, isExport) => {
  let params: any = {};
  params.materialCode = searchForm.materialCode;
  params.orderSn = searchForm.orderSn;
  params.projectName = searchForm.projectName;
  params.supplierName = searchForm.supplierName;
  params.projectReconciliationStatus = searchForm.projectReconciliationStatus;
  params.settlementStatus = searchForm.settlementStatus;
  params.projectInvoiceStatus = searchForm.projectInvoiceStatus;
  params.contractNo = searchForm.contractNo;
  params.auditStatus = searchForm.auditStatus;
  params.beginDate = searchForm.date == undefined ? "" : searchForm.date[0];
  params.endDate = searchForm.date == undefined ? "" : searchForm.date[1];
  params.contractMethod = 1;
  if(isExport) {
    await http.request('get',baseUrlApi("projectOrder/export/file"), {params})
    return
  }
  if (query === "1") {
    tablePage.currentPage = 1;
  }

  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  getprojectOrderlist(params).then((response: any) => {
    response.data.records.forEach(res => {
      if (res.priceType == "0") {
        res.priceType = "锁定";
      } else if (res.priceType == "1") {
        res.priceType = "浮动";
      }
    });
    ProjectOrderTableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  });
  if (query) {
    setTimeout(() => {
      getprojectOrderlist;
    }, 1500);
  }
};
// 删除项目订单
const del = row => {
  ElMessageBox.confirm("确认删除选中的合同吗？", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let params: any = {};
      params.id = row.id;
      deleteprojectOrder(params).then((response: any) => {
        if (response.code == "200") {
          ElMessage({
            message: "删除成功",
            type: "success"
          });
          getlist();
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled"
      // });
    });
};

// 表格数据
const ProjectOrderTableData = ref([]);

// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

// 清空按钮点击事件
const clearAllFields = () => {
  // 重置SearchForm对象的所有属性
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "signDate") {
        // searchForm[key] = [];
        searchForm[key] = null;
      } else {
        searchForm[key] = "";
      }
    }
  }
};

// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getlist();
};

//弹窗打开
let dialogVisible = ref(false);
function showSalescontract() {
  dialogVisible.value = true;
}
function closeSales(val: boolean) {
  dialogVisible.value = false;
}

//供货完成
async function getOrderType(row) {
  let params: ApiParams = {};
  params.projectId = row.id;
  const response: ApiResponse = await getSupplyTypeCheck(params);
  if (response.code == "200") {
    switch (response.data.ifSupplied) {
      // 部分供货
      case "0":
        goGHWC(row, "0");
        break;
      // 完全供货
      case "1":
        goGHWC(row, "1");
        break;
    }
  }
}
const goGHWC = (row, type) => {
  ElMessageBox.confirm(
    type === "0" ? "当前未完全供货，是否供货完成" : "确认订单供货完成吗?",
    "",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      let params: any = {};
      params.id = row.id;
      postsupplyFinished(params).then((response: any) => {
        if (response.code == "200") {
          ElMessage({
            message: "供货完成",
            type: "success"
          });
          getlist();
        }
      });
    })
    .catch(() => {});
};

//提交审批
async function Submit(row) {
  ElMessageBox.confirm("确认提交该订单审批吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let params: any = {};
      params.id = row.id;
      postsubmitapproval(params).then((response: any) => {
        if (response.code == "200") {
          ElMessage({
            message: "提交成功",
            type: "success"
          });
          getlist();
        }
      });
    })
    .catch(() => {
      ElMessage.info("取消提交！");
    });
}
// 项目名称选择
let projectOptions = ref([]);
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query,
    contractMethod:1
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
</script>

<style lang="scss" scoped></style>
